//
//  CCHorizontalEquidistanceFlowLayout.m
//  CCFoundation
//
//  Created by zjh on 2021/9/24.
//

#import "CCHorizontalEquidistanceFlowLayout.h"
@interface CCHorizontalEquidistanceFlowLayout ()
@property (nonatomic, strong) NSMutableArray *itemAttributes;
@end
@implementation CCHorizontalEquidistanceFlowLayout
- (void) prepareLayout {
    [super prepareLayout];
    NSInteger itemCount = [[self collectionView] numberOfItemsInSection:0];
    self.itemAttributes = [NSMutableArray arrayWithCapacity:itemCount];
    
    CGFloat xOffset = self.sectionInset.left;
    CGFloat yOffset = self.sectionInset.top;
    CGFloat xNextOffset = self.sectionInset.left;
    for (NSInteger idx = 0; idx < itemCount; idx++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:idx inSection:0];
        CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
        if (idx == 0) {
            xNextOffset += itemSize.width;
        } else {
            xNextOffset += (self.minimumInteritemSpacing + itemSize.width);
        }
        if (xNextOffset > [self collectionView].bounds.size.width - self.sectionInset.right) {
            xOffset = self.sectionInset.left;
            xNextOffset = (self.sectionInset.left + self.minimumInteritemSpacing + itemSize.width);
            yOffset += (itemSize.height + self.minimumLineSpacing);
        } else {
            xOffset = xNextOffset - (self.minimumInteritemSpacing + itemSize.width);
        }
        if (xOffset < 0) {
            xOffset = 0;
        }
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        layoutAttributes.frame = CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height);
        [_itemAttributes addObject:layoutAttributes];
    }
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return (self.itemAttributes)[indexPath.item];
}
 
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return [self.itemAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *evaluatedObject, NSDictionary *bindings) {
        return CGRectIntersectsRect(rect, [evaluatedObject frame]);
    }]];
}

/// 不重写这个方法，在模拟器下会一直调用updateVisibleCellsNows
- (BOOL)shouldInvalidateLayoutForPreferredLayoutAttributes:(UICollectionViewLayoutAttributes *)preferredAttributes withOriginalAttributes:(UICollectionViewLayoutAttributes *)originalAttributes {
    return NO;
}

/// 模拟器下只重写该方法，不会被调用，导致一直调用updateVisibleCellsNows
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return NO;
}
@end
